import { Alert, Form, Select, Space, Popover, Modal, message } from 'antd';
import { useState, useEffect, useMemo, useRef } from 'react';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { getAllPrinter, checkComponentsIsOpen } from "@/utils/print.jsx";
import Api from '@/pages/OrderModule/orderList/components/Actions/service';

const { Option } = Select;

export default ({ len, selectedRows = [], handleSavaPrint, fetchList, orderList, onCancel }) => {

  const [visible, setVisible] = useState(false);
  //打印机列表
  const [data, setData] = useState([]);
  const [sourceData, setSourceData] = useState([]);

  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false);

  const configObj = useRef(JSON.parse(localStorage.getItem("warehouse-express-printer")) || {});

  useEffect(() => {
    setVisible(true);
    getAllPrinter(value => setData(value));
		getPrintDataFunc();
    // Modal.confirm({
    //   title:'打印提示',
    //   okText: '确定打印',
    //   content: <>
    //   <div>当前勾选了<span className='common-color2'>5</span>个仓库的订单</div>
    //   <p>不同仓库订单同时打印，则订单会按不同仓库分类分开打，同时记录<span className='common-color9'>不同打印批次</span>。</p>
    //   <div>请确认是否需要一起打印？</div>
    //   </>,
    //   onOk(){
    //     console.log('zhixngle')
    //   }
    // })
    form.resetFields()
  }, [])

  const getPrintDataFunc = async () => {
    const selectKeys = selectedRows.map(v => v.id);
    const systemNos = orderList.filter(v => selectKeys.includes(v.id)).map(v => v.systemNo);
    setLoading(true);
    const { data, success} = await Api.getPrintDataOp({ systemNos, printPageType: 1 });
    setLoading(false);
    if(success){
      if(!data?.length){
        return message.info('暂未获取到打印数据。');
      }
      setSourceData(data);
    }
  }

  const computeObj = useMemo(()=>{
    let platform = [], nums = 0, repeatNums = 0;
    sourceData.map(child=>{
      child.items.map(item=>{
        item.printer = configObj.current[child.warehouseName+'@'+item.expressName];
        platform.push(item.printLogisticsList[0]?.platform);
        nums += item.printLogisticsList?.length || 0;
        item.printLogisticsList.map(printObj=>{
          printObj.printState && repeatNums ++;
          printObj.printTaskId = item.printTaskId;
          printObj.logPage = 20;
        })
      })
    })
    platform = [...new Set(platform)];
    return { platform, nums, repeatNums }
  }, [sourceData])

  const { platform, nums, repeatNums } = computeObj;

  const onOk = () => {
    form.validateFields().then(config=>{
      setLoading(true);
      //校验打印组件
      checkComponentsIsOpen(platform, (res)=>{
        setLoading(false);
          if(res.status){
            //更新存储
            localStorage.setItem("warehouse-express-printer", JSON.stringify(configObj.current));
            //记录打印记录
            const taskArr = [];
            sourceData.map(child=>{
              child.items.map(item=>{
                taskArr.push({
                  taskId: item.printTaskId,
                  printerName: item.printer
                })
              })
            })
            Api.setPrinterNamesOp(taskArr);
            //提示数量
            Modal.info({
              centered: true,
              title: "打印提示",
              content: (
                <div style={{ color: "#333", marginTop: 24 }}>
                  <Space size={8} direction='vertical'>
                    <span>成功数：<span className='common-color10' style={{fontWeight:'bold'}}>{nums}</span></span>
                    <span>失败数：<span className='common-color9' style={{fontWeight:'bold'}}>0</span></span>
                  </Space>
                </div>
              ),
              onOk(){
                setTimeout(()=>{
                  fetchList();
                }, 800)
              }
            });
            //推送打印数据
           const printData = [];
           sourceData.map(item=>{
            item.items.map(child=>{
              child.printLogisticsList.map(printItem=>{
                printData.push({
                  ...printItem,
                  printer: child.printer
                })
              })
            })
           })
            handleSavaPrint(printData);
            setVisible(false);
          }
        })
    })
  }

  const options = useMemo(() => {
    if (data?.length) {
      return data.map(d => <Option key={d} value={d}>{d}</Option>)
    }
  }, [data])

  // 设置打印机名称
  const handleSelectPrinter = (field, printer, index, indexs) => {
    configObj.current ={
      ...configObj.current,
      [field]: printer
    }
    sourceData[index]['items'][indexs].printer = printer;
    // console.log(sourceData,field, printer, index, indexs);
  }

  return <CommonModal
    width={560}
    visible={visible}
    title='打印快递单'
    onOk={onOk}
    onCancel={()=>setVisible(false)}
    afterClose={onCancel}
  >
    {/* <Alert showIcon type="info" message={<><p>可打印订单数：即有快递和运单号的订单；</p>
      <div>快递、无运单号、手动输入的运单号、代发订单，都将不会统计在内</div>
    </>} /> */}
    <div style={{padding:'16px 0'}}>
      <p>勾选订单数：<span style={{fontWeight:'bold'}}>{len}</span></p>
      <p>可打印订单数：<span style={{fontWeight:'bold'}}>{nums}</span></p>
      {/* { !!repeatNums && <div>即将重复打印的订单数：<span style={{fontWeight:'bold'}}>{repeatNums}</span>
      <span className='common-color10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;请确认是否需要重复打印</span>
      </div>} */}
    </div>
    
    <Form name="hot-selectprinter" form={form} initialValues={configObj.current} layout='vertical'>
      {
        sourceData.map((child, index) => (<>
          <h4 style={{fontWeight:'bold', marginBottom:'6px'}}>{index + 1}、{child.warehouseName}<span style={{ color: '#ff2d51', marginLeft: '12px'}}>{child.printableQuantity}单</span></h4>
          {
            child.items.map((item, indexs) => {
              const { expressName } = item, field = child.warehouseName + "@" + expressName;
              return (<Form.Item
                label={<Popover content={expressName}><span className="textOverflowMultiOne">{expressName}</span></Popover>}
                name={field}
                rules={[{ required: true, message: '请选择打印机' }]}
                key={field}
                style={{marginTop:'4px'}}
              >
                <Select
                  allowClear
                  placeholder="请选择打印机"
                  onChange={(e) => handleSelectPrinter(field, e, index, indexs)}
                >
                  {options}
                </Select>
              </Form.Item>)
            })
          }
        </>
        ))
      }
    </Form>
    <CommonLoading loading={loading} />
  </CommonModal>
}